package com.wm.dao.hibernate;

import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.wm.bean.Address;
import com.wm.bean.User;
import com.wm.dao.AddressDAO;

/**
 * @author yangbo
 *
 * 2012-12-26
 */
public class AddressHibernateDAO extends HibernateDaoSupport implements AddressDAO {
	
	private static final String LOAD_BY_ID = "from Address where id = ?";
	private static final String LOAD_BY_USERID = "from Address where userId = ?";
	private static final String LOAD_BY_PHONE = "from Address where phone = ?";
	private static final String LOAD_BY_BACKPHONE = "from Address where backPhone = ?";
	private static final String LOAD_BY_ADDRESS = "from Address where address = ?";
	private static final String LOAD_BY_KEYWORD = "from Address where address like ?";
	private static final String LOAD_BY_USERID_ISDEFAULT = "from Address where userId = ? and isDefault = 1";

	/**
	 * 保存
	 * @param a
	 * @return
	 */
	public Address saveAddress(Address a){
		this.getHibernateTemplate().save(a);
		return a;
	}
	
	/**
	 * 修改
	 * @param a
	 * @return
	 */
	public Address updateAddress(Address a){
		this.getHibernateTemplate().update(a);
		return a;
	}
	
	/**
	 * 删除
	 * @param a
	 */
	public void removeAddress(Address a){
		this.getHibernateTemplate().delete(a);
	}
	
	/**
	 * 根据ID查询
	 * @param id
	 * @return
	 */
	public Address findAddressById(long id){
		Object[] obj={new Long(id)};
		List l = this.getHibernateTemplate().find(LOAD_BY_ID,obj);
		if(l == null || l.isEmpty()){
			return null;
		}else{
			return (Address) l.get(0);
		}
	}
	
	/**
	 * 根据用户ID查询
	 * @param userId
	 * @return
	 */
	public List findAddressByUserId(long userId){
		return this.getHibernateTemplate().find(LOAD_BY_USERID,new Long(userId));
	}
	
	/**
	 * 根据电话查询
	 * @param phone
	 * @return
	 */
	public List findAddressByPhone(String phone){
		return this.getHibernateTemplate().find(LOAD_BY_PHONE,phone);
	}
	
	/**
	 * 根据备用电话查询
	 * @param backPhone
	 * @return
	 */
	public List findBackPhone(String backPhone){
		return this.getHibernateTemplate().find(LOAD_BY_BACKPHONE,backPhone);
	}
	
	/**
	 * 根据地址查询
	 * @param address
	 * @return
	 */
	public List findAddressByAddress(String address){
		return this.getHibernateTemplate().find(LOAD_BY_ADDRESS,address);
	}
	
	/**
	 * 根据地址模糊查询
	 * @param address
	 * @return
	 */
	public List findAddressByKeyword(String keyword){
		return this.getHibernateTemplate().find(LOAD_BY_KEYWORD,"%"+keyword+"%");
	}
	
	/**
	 * 查询默认地址
	 * @return
	 */
	public Address findAddressByIsUserIdDefault(long userId){
		Object[] obj={new Long(userId)};
		List l = this.getHibernateTemplate().find(LOAD_BY_USERID_ISDEFAULT,obj);
		if(l == null || l.isEmpty()){
			return null;
		}else{
			return (Address) l.get(0);
		}
	}
}
